package com.cuijq.dubbo.core.server;

import com.cuijq.dubbo.demo.Invocation;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;

@Slf4j
@ChannelHandler.Sharable
public class NettyServerHandle extends ChannelInboundHandlerAdapter implements ApplicationContextAware {
    ApplicationContext applicationContext;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Invocation invocation = (Invocation) msg;
        String interfaceName = invocation.getInterfaceName();
        String methodName = invocation.getMethodName();
        Class clazzInterface = Class.forName(interfaceName);
        String className = applicationContext.getBeanNamesForType(clazzInterface)[0];
        Class clazz = applicationContext.getBean(className).getClass();
        Method method = clazz.getMethod(methodName, invocation.getParamTypes());
        String result = (String) method.invoke(clazz.newInstance(), invocation.getParam());
        log.info("接收tcp协议:{}", result);
        ctx.writeAndFlush(result);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
